﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace HMS.Hosting.Authentication.Cookies;

public class MemoryTicketStore : ITicketStore
{
    private readonly IDictionary<string, AuthenticationTicket> _ticketCache = new Dictionary<string, AuthenticationTicket>();

    public Task RemoveAsync(string key)
    {
        if (_ticketCache.ContainsKey(key))
        {
            _ticketCache.Remove(key);
        }

        return Task.CompletedTask;
    }

    public Task RenewAsync(string key, AuthenticationTicket ticket)
    {
        if (_ticketCache.ContainsKey(key))
        {
            _ticketCache[key] = ticket;
        }

        return Task.CompletedTask;
    }

    public Task<AuthenticationTicket?> RetrieveAsync(string key)
    {
        _ticketCache.TryGetValue(key, out var ticket);

        return Task.FromResult(ticket);
    }

    public Task<string> StoreAsync(AuthenticationTicket ticket)
    {
        var id = Guid.NewGuid().ToString("D").Replace("-", "");

        _ticketCache.Add(id, ticket);

        return Task.FromResult(id);
    }
}